import { DataTableComponent, DialogService, TableWidthConfig, TreeComponent } from 'ng-devui';
import { SupplierService } from './../../../@core/services/supplier/supplier.service';
import { Component, ViewChild } from '@angular/core';
import { SupplierClassAddComponent } from './supplier-class-add/supplier-class-add.component';
import { SupplierClassEditComponent } from './supplier-class-edit/supplier-class-edit.component';
import { SharedMethodService } from 'src/app/@core/services/Sharedmethod/shared-method.service';
import { Route, Router } from '@angular/router';
@Component({
  selector: 'app-supplier',
  templateUrl: './supplier.component.html',
  styleUrls: ['./supplier.component.scss']
})
export class SupplierComponent {
  displayTreeData: any[] = []
  supplierTypeId: any;
  msgs: Array<Object> = [];
  option: any;
  filter={
    SupplyClassId:null,
    PageSize:20,
    PageNumber:1,
    SearchTerm:null,
    SearchStatus:null
  }
  statusoptions = [
    '全部','启用','禁用'
  ]
  pathPids = []//树结构路径
  config = {
    maxHeight: '400px',
    width: '400px',
    backdropCloseable: true,
  }//弹窗配置
  treeData: any=[
    {
        "supplyClassId": 1,
        "supplyClassName": "老供",
        "note": "老供应商",
        "parentSupplyClassId": null,
        "parentSupplyClassName": null,
        "subSupplyClasses": [
            {
                "supplyClassId": 2,
                "supplyClassName": "测试供应商类别A",
                "note": "aaaaaaa",
                "parentSupplyClassId": 1,
                "parentSupplyClassName": "老供",
                "subSupplyClasses": [
                 ]
            },
            {
                "supplyClassId": 3,
                "supplyClassName": "物料A的供应商",
                "note": null,
                "parentSupplyClassId": 1,
                "parentSupplyClassName": "老供",
                "subSupplyClasses": [
                 ]
            }
        ]
    }
  ]
  tabledata=[ ]
  pageSizeOptions = [10, 20, 30, 50, 100];
  pager = {
    total:1
  }
  dataTableOptions = {
    columns: [
      {
        field: 'code',
        header: '供应商编码',
        fieldType: 'text',
        fixedLeft: '150px'
      },
      {
        field: 'name',
        header: '供应商名称',
        fieldType: 'text',
        fixedLeft: '300px'
      },
      {
        field: 'workCode',
        header: '供应商简称',
        fieldType: 'text'
      },
      {
        field: 'account',
        header: '英文名称',
        fieldType: 'text'
      },
      {
        field: 'departmentName',
        header: '类别',
        fieldType: 'text'
      },
      {
        field: 'gender',
        header: '业务员',
        fieldType: 'text'
      },
      {
        field: 'mobile',
        header: '联络对象',
        fieldType: 'text'
      },
      {
        field: 'bankName',
        header: '电话',
        fieldType: 'text'
      },
      {
        field: 'bankHolder',
        header: '联系地址',
        fieldType: 'text'
      },
      {
        field: 'wechat',
        header: '传真',
        fieldType: 'text'
      },
      {
        field: 'contractStartDate',
        header: '邮箱',
        fieldType: 'text'
      },
      {
        field: 'idNumber',
        header: '是否开票',
        fieldType: 'text'
      },
      {
        field: 'email',
        header: '营业税率',
        fieldType: 'text'
      },
      {
        field: 'insuranceState',
        header: '付款账期',
        fieldType: 'text'
      },
      {
        field: 'isStay',
        header: '结算方式',
        fieldType: 'boolean'
      },
      {
        field: 'salaryType',
        header: '交易币种',
        fieldType: 'text'
      },
      {
        field: 'contractStartDate',
        header: '状态',
        fieldType: 'text'
      },
      {
        field: 'enabled',
        header: '备注',
        fieldType: 'boolean',
      },
      {
        field: 'enabled',
        header: '创建时间',
        fieldType: 'boolean',
      },
    ]
  };//表头数据
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '40px'
    },
    {
      field: '操作',
      width: '110px'
    },
    {
      field: '供应商编码',
      width: '150px'
    },
    {
      field: '供应商名称',
      width: '200px'
    },
    {
      field: '供应商简称',
      width: '150px'
    },
    {
      field: '英文名称',
      width: '150px'
    },
    {
      field: '类别',
      width: '150px'
    },
    {
      field: '业务员',
      width: '150px'
    },
    {
      field: '联络对象',
      width: '150px'
    },
    {
      field: '电话',
      width: '150px'
    },
    {
      field: '联系地址',
      width: '280px'
    },
    {
      field: '传真',
      width: '150px'
    },
    {
      field: '邮箱',
      width: '150px'
    },
    {
      field: '是否开票',
      width: '150px'
    },
    {
      field: '营业税率',
      width: '150px'
    },
    {
      field: '付款账期',
      width: '150px'
    },
    {
      field: '结算方式',
      width: '150px'
    },
    {
      field: '交易币种',
      width: '150px'
    },
    {
      field: '状态',
      width: '150px'
    },
    {
      field: '备注',
      width: '150px'
    },
    {
      field: '创建时间',
      width: '160px'
    }
  ];//表格宽度配置
  searchValue: any;
  @ViewChild('fileInput') fileInput: any;
  filteredTreeNodes: any[];
  @ViewChild('basicTree', { static: true }) basicTree!: TreeComponent;
  @ViewChild(DataTableComponent, { static: true }) datatable!: DataTableComponent;
  checkedIds: any=[]
  file: any;
  constructor(private SupplierService:SupplierService,private dialogService:DialogService,private SharedMethodService:SharedMethodService,private router:Router){}
  ngOnInit(){
    this.SupplierService.getSupplierClass().subscribe((res:any)=>{
      this.treeData = res
      this.displayTreeData = [{ supplyClassName: '全部', supplyClassId: null }, ...this.treeData]
    })
    this.SupplierService.getSupplier(this.filter).subscribe((res:any)=>{
      this.tabledata = res.items
    })
  }
  afterTreeInit($event: any) {
    if ($event && Object.keys($event).length > 0) {
      if ($event[1].data.title=='全部') {
        $event[1].data.isActive = true
      }
    }
  }//树形菜单初始化
  nodeSelected($event:any){
    this.option = $event.data.originItem
    this.supplierTypeId = $event.data.originItem.supplyClassId;
    this.filter.SupplyClassId = this.supplierTypeId
    this.search()
    this.pathPids = this.getPathPids(this.option, this.treeData);// 输出路径 PID
    console.log(this.pathPids)
  }
  creatType(dialogtype?: string){
    let data = {
      options: this.treeData,
      pathPids: this.pathPids,
      display: false
    };
    const results = this.dialogService.open({
      id: 'department',
      ...this.config,
      title: '新建类别',
      data: data,
      content: SupplierClassAddComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.supplyClassName) {
             this.SupplierService.addSupplierClass(results.modalContentInstance.form).subscribe((res:any)=>{
              results.modalInstance.hide();
                this.showToast('success', '成功', '新建成功')
                this.SupplierService.getSupplierClass().subscribe((res:any)=>{
                  this.treeData = res
                  this.displayTreeData = [{ supplyClassName: '全部', supplyClassId: null }, ...this.treeData]})
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
            )
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  editType(dialogtype?: string){
    if (this.supplierTypeId) {
      let data = {
        options: this.treeData,
        pathPids: this.pathPids.slice(0, -1),
        display: false,
        option: this.option
      };
      const results = this.dialogService.open({
        id: 'department',
        ...this.config,
        title: '编辑部门',
        data: data,
        content: SupplierClassEditComponent,
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
              if (results.modalContentInstance.form.supplyClassName) {
                this.SupplierService.editSupplierClass(results.modalContentInstance.form.supplyClassId,results.modalContentInstance.form).subscribe((res:any)=>{
                  this.showToast('success', '成功', '编辑成功')
                  results.modalInstance.hide();
                  this.SupplierService.getSupplierClass().subscribe((res:any)=>{
                    this.treeData = res
                    this.displayTreeData = [{ supplyClassName: '全部', supplyClassId: null }, ...this.treeData]})
                },(error) => {
                  if(error.status==404){
                    this.showToast('error', '失败', '服务器连接失败');
                  }else{
                    this.showToast('error', '失败', error.error);
                  }
                }
              )
              }
              data.display = true;
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }
  deleteType(dialogtype?: string){
    if (this.supplierTypeId) {
      const results = this.dialogService.open({
        ...this.config,
        title: '删除',
        content: '确认删除该类别？',
        dialogtype: dialogtype,
        onClose: () => {
        },
        buttons: [
          {
            cssClass: 'stress',
            text: '确定',
            handler: ($event: Event) => {
             this.SupplierService.deleteSupplierClass(this.supplierTypeId).subscribe((res:any)=>{
                this.showToast('success', '成功', '删除成功')
                results.modalInstance.hide();
                this.SupplierService.getSupplierClass().subscribe((res:any)=>{
                  this.treeData = res
                  this.displayTreeData = [{ supplyClassName: '全部', supplyClassId: null }, ...this.treeData]})
                  results.modalInstance.hide();
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
            )
            },
          },
          {
            id: 'btn-cancel',
            cssClass: 'common',
            text: '取消',
            handler: ($event: Event) => {
              results.modalInstance.hide();
            },
          },
        ],
      });
    }
  }
  searchMaterialCategory($event:any){
    this.searchValue = $event.target.value;
    if (this.searchValue === '') {
      // 如果用户输入的值为空，显示原先的数据
      this.displayTreeData = this.displayTreeData = [{ supplyClassName: '全部',supplyClassId:null}, ...this.treeData];
    } else {
      this.filteredTreeNodes = this.filterCategories(this.treeData, this.searchValue);
      this.displayTreeData = this.filteredTreeNodes
      this.displayTreeData = this.displayTreeData.map(this.setOpenTrue);
    }
  }//搜索仓库类目
  getPathPids(node: any, nodes: any[]) {
    for (let item of nodes) {
      let path = this.traverse(item, node.supplyClassId)
      if (path) {
        return path
      }
    }
    return null
  }//获取树形菜单pid的路径

  traverse(node: any, id: any, path = []) {
    path.push(node.supplyClassId);
    if (node.supplyClassId === id) {
      return path;
    }
    for (let child of node.subSupplyClasses) {
      let result = this.traverse(child, id, [...path]);
      if (result) {
        return result;
      }
    }
    return null;
  }//获取树形菜单pid的路径
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  filterCategories(categories: any[], keyword: string): any[] {
    const result: any[] = [];
    for (const category of categories) {
      if (category.supplyClassName.includes(keyword)) {
        result.push(category);
      }
      if (category.subSupplyClasses.length > 0) {
        const filteredSubCategories = this.filterCategories(category.subSupplyClasses, keyword);
        if (filteredSubCategories.length > 0) {
          result.push(...filteredSubCategories);
        }
      }
    }
    return result;
  }
  setOpenTrue = (node: any) => {
    // 为当前节点添加 open: true 属性
    node.open = true;
    // 如果当前节点有子节点，递归处理子节点
    if (Array.isArray(node.subSupplyClasses)) {
      node.subSupplyClasses = node.subSupplyClasses.map(this.setOpenTrue);
    }
    return node;
  }
  search(){
    this.SupplierService.getSupplier(this.filter).subscribe((res:any)=>{
      this.tabledata = res.items
    })
  }
  search2(){
    this.filter.PageNumber = 1
    this.SupplierService.getSupplier(this.filter).subscribe((res:any)=>{
      this.tabledata = res.items
    })
  }
  reset(){
    this.filter = {
      SupplyClassId:null,
      PageSize:20,
      PageNumber:1,
      SearchTerm:null,
      SearchStatus:null
    }
    this.search()
  }
  addSupplier(){
    this.router.navigate(['/pages/basicdata/supplier/supplier-add'])
  }
  editSupplier(id:any){
    this.router.navigate(['/pages/basicdata/supplier/supplier-edit',id])
  }
  enable(id?:any){
    if(id){
      this.SupplierService.enableSupplier([id]).subscribe((res:any)=>{
        this.showToast('success', '成功', '启用成功')
        this.checkedIds=[]
        this.search()

      }
    ),(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
    }else{
      this.SupplierService.enableSupplier(this.checkedIds).subscribe((res:any)=>{
        this.showToast('success', '成功', '启用成功')
        this.checkedIds =[]
        this.search()
      }),(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
    }
  }
  disable(id?:any){
    if(id){
      this.SupplierService.disableSupplier([id]).subscribe((res:any)=>{
        this.showToast('success', '成功', '禁用成功')
        this.search()
        this.checkedIds=[]
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
    )
    }else{
      this.SupplierService.disableSupplier(this.checkedIds).subscribe((res:any)=>{
        this.showToast('success', '成功', '禁用成功')
        this.search()
        this.checkedIds=[]
      },(error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
    )
    }
  }
  deleteSupplier(id?:any,dialogtype?: string){
    const results = this.dialogService.open({
      ...this.config,
      title: '删除',
      content: '确认删除该供应商？',
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if(id){
              this.SupplierService.deleteSupplier([id]).subscribe((res:any)=>{
                this.showToast('success', '成功', '删除成功')
                this.search()
                this.checkedIds=[]
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
            )
            }else{
              this.SupplierService.deleteSupplier(this.checkedIds).subscribe((res:any)=>{
                this.showToast('success', '成功', '删除成功')
                this.search()
              },(error) => {
                if(error.status==404){
                  this.showToast('error', '失败', '服务器连接失败');
                }else{
                  this.showToast('error', '失败', error.error);
                }
              }
            )
            }
            results.modalInstance.hide()
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  pageIndexChange(){
    this.search()
  }
  pageSizeChange(){
    this.search()
  }
  onRowCheckChange(checked: any, rowIndex: any, nestedIndex: any, rowItem: { $checked: any; $halfChecked: boolean; }) {
    this.SharedMethodService.onRowCheckChange(checked, rowIndex, nestedIndex, rowItem, this.datatable)
  }
  getCheckedRows() {
    this.SharedMethodService.getCheckedRows(this.datatable, 'supplyId').subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//获取选中行
  cleared() {
    this.SharedMethodService.cleared(this.checkedIds, this.tabledata, this.datatable).subscribe((data: any) => {
      this.checkedIds = data;
    })
  }//清空选中行
  onFileSelected(event: any) {
    // 当用户选择了Excel文件时，将其赋值给组件的file属性
    this.file = event.target.files[0];
    this.SupplierService.importSupplierFromExcel(this.file).subscribe((data: any) => {
      this.showToast('success', '成功', '导入成功')
      this.search()
      event.target.value = null;
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }//导入员工
  onButtonClick(){
    // 当按钮被点击时，触发文件输入的点击事件
    this.fileInput.nativeElement.click();
  }
  DownloadSupplierFileModel(){
    this.SupplierService.DownloadSupplierExcelModel().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '供应商信息模板.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }
  DownloadSupplierFile(){
    this.SupplierService.DownloadSupplierExcelFile().subscribe((data:any)=>{
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      a.setAttribute('download', '供应商信息.xlsx');
      a.click();
      URL.revokeObjectURL(objectUrl);
    },(error) => {
      if(error.status==404){
        this.showToast('error', '失败', '服务器连接失败');
      }else{
        this.showToast('error', '失败', error.error);
      }
    }
  )
  }
}
